// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables, use_build_context_synchronously
import 'package:flutter/material.dart';
import 'package:junyeyishu/ui/sale/widgets/QGAlert.dart';
import 'package:junyeyishu/ui/sale/widgets/QGPasswordAlert.dart';
import 'widgets/QGPurchaseNFTListWidget.dart';

import 'package:junyeyishu/utils/utils.dart';
import 'package:junyeyishu/widgets/QGWidget.dart';
import 'package:junyeyishu/widgets/QGButton.dart';
import 'dart:math';

import 'package:sprintf/sprintf.dart';

class QGPurchaseConfirmPage extends StatefulWidget {
  dynamic args;
  QGPurchaseConfirmPage({super.key, this.args});
  @override
  State<QGPurchaseConfirmPage> createState() => QGPurchaseConfirmPageState();
}

class QGPurchaseConfirmPageState extends State<QGPurchaseConfirmPage> {
  dynamic data;
  @override
  void initState() {
    super.initState();
    data = widget.args;
  }
 
  @override
  Widget build(BuildContext context) {
    return QGScaffold(
        title: data?["ttype"] == 2?'求购':"委托",
        bgColor: Color(0xFF0C1012),
        body: Column(
          children: [
            Expanded(
              child: Stack(
                children: [
                  Padding(
                    padding: EdgeInsets.all(10.rpx),
                    child: ListView(
                      children: [
                        Column(
                          children: [
                            buildHeader(),
                            SizedBox(height: 10.rpx),
                            buildIncome(),
                            SizedBox(height: 10.rpx),
                            buildExtra(),
                            SizedBox(height: 65.rpx + max(10, kSafeBottom)),
                          ],
                        ),
                      ],
                    ),
                  ),
                  Positioned(
                    bottom: 0,
                    left: 0,
                    right: 0,
                    child: buildBottom(),
                  )
                ],
              ),
            ),
          ],
        ));
  }

  buildHeader() {
    return Container(
      padding: EdgeInsets.all(15.rpx),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.rpx),
        color: Color(0xFF232A32),
      ),
      child: Row(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(6.rpx),
            child:
                QGImage(url: data?["thumb_img"], width: 80.rpx, height: 80.rpx),
          ),
          SizedBox(width: 15.rpx),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                buildText(data?["name"] ?? "", 15.rpx, FontWeight.bold,
                    Color(0xFFffffff)),
                SizedBox(height: 10.rpx),
                buildNo(),
                SizedBox(height: 10.rpx),
                buildInfo(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  buildNo() {
    return Row(
      children: [
        buildText("#${data?['random_nft_no']}", 12.rpx,
            FontWeight.normal, Color(0xFFffffff)),
        // SizedBox(width: 7.rpx),
        // QGImage(asset: "sale_exchange_icon", width: 14.rpx)
      ],
    );

    // return GestureDetector(
    //   onTap: toSwitchNo,
    //   child: Row(
    //     children: [
    //       buildText("#${data?['nft_no']}/${data?['total']}", 13.rpx,
    //           FontWeight.normal, Color(0xFF111111)),
    //       SizedBox(width: 7.rpx),
    //       QGImage(asset: "sale_exchange_icon", width: 14.rpx)
    //     ],
    //   ),
    // );
  }

  buildInfo() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        buildText("拥有数量: ${data?["own_num"]}", 11.rpx, FontWeight.normal,
            Color(0XFF999999)
            ),
        // Flexible(
        //     child: buildText("出售价:￥${data?["order_price"]}", 14.rpx,
        //         FontWeight.normal, Color(0xFFffffff))),
      ],
    );
  }

  buildText(text, size, weight, color) {
    return Text(
      text,
      style: TextStyle(color: color, fontSize: size, fontWeight: weight),
    );
  }

  buildIncome() {
    var price = double.parse(data?["order_price"]);
    var fee = sprintf("%.2f", [price * 0.05]);
    var income = sprintf("%.2f", [price * 0.95]);

    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.rpx),
        color:Color(0XFF232A32)
      ),
      padding: EdgeInsets.all(15.rpx),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          buildText('预计收入', 14.rpx, FontWeight.normal, Color(0xFFFFFFFF)),
          SizedBox(height: 6.rpx),
          buildItem("总售价：", "￥${data?["order_price"]}"),
          buildItem("综合服务费(5%)：", "$fee"),
          buildItem("预计收入：", "￥$income"),
        ],
      ),
    );
  }

  buildItem(title, value) {
    return GestureDetector(
      child: Container(
        color: Colors.transparent,
        padding: EdgeInsets.symmetric(vertical: 8.rpx),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              title ?? "",
              style: TextStyle(
                  color: Color(0XFF999999),
                  fontSize: 12.rpx,
                  fontWeight: FontWeight.normal),
            ),
            Container(
              color: Colors.transparent,
              child: Row(
                children: [
                  Text(
                    value ?? "",
                    style: TextStyle(
                        color: Color(0xFFFFFFFF),
                        fontSize: 12.rpx,
                        fontWeight: FontWeight.normal),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  buildExtra() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.rpx),
                color:Color(0XFF232A32)
      ),
      padding: EdgeInsets.all(15.rpx),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Expanded(
            child: Text(
              """以求购价出售说明：
1.成交顺序是以买方发起求购订单的金额由高至低的顺序成交。
2.买方求购订单的付款钱包和卖方收款账户钱包需要一致才可成交，如果不一致会导致无法成交。
3.订单一旦成交，不可撤销。""",
              style: TextStyle(
                  height: 1.6,
                  color: Color(0xFFb8b8b8),
                  fontSize: 11.rpx,
                  fontWeight: FontWeight.bold),
            ),
          ),
        ],
      ),
    );
  }

  buildBottom() {
    return Container(
      padding: EdgeInsets.only(
          left: 10.rpx,
          right: 10.rpx,
          bottom: max(10, kSafeBottom),
          top: 10.rpx),
      decoration: BoxDecoration(
        color: Color(0xFF232A32),
      ),
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        Text(
          "￥${data?["order_price"]}",
          style: TextStyle(
              color: Color(0xFFFFFFFF),
              fontSize: 20.rpx,
              fontWeight: FontWeight.bold),
        ),
        Flexible(
          child: Container(
              alignment: Alignment.center,
              height: 44.rpx,
              width: 210.rpx,
              child: QGButton(
                title: "确认出售",
                onTap: onPay,
              )),
        )
      ]),
    );
  }

  toSwitchNo() {
    QGPurchaseNFTListWidget.show(context, data, (selectId, selectNo) {
      data?["nft_id"] = selectId;
      data?["nft_no"] = selectNo;
      if (mounted) setState(() {});
    });
    data["select_no"] = data?["nft_no"];
  }

  onPay() {
    QGAlert.show(context,
        title: "￥${data?["order_price"]}",
        content: "您确定以${data?["order_price"]}元出售吗？",
        confirm: "确定",
        onConfirm: toConfirm);
  }

  toConfirm() async {
    
    Navigator.of(context).pop();
    await Future.delayed(const Duration(milliseconds: 300));

    QGPasswordAlert.show(context, onConfirm: (pwd) {
      var param = {};
      param['out_trade_no'] = data?["out_trade_no"];
      param['nft_no'] = data?['random_nft_no'];
      param['pay_passwd'] = pwd;
Map<String, dynamic> stringMap = param.cast<String, dynamic>();

      dynamic urlpickOrder;

        if(data?['ttype']==2){
          urlpickOrder = url_ask_pickOrder;
        }else{
          urlpickOrder = url_entrust_pickOrder;
        }
        

      Network.post(urlpickOrder, data: stringMap, context: context)
          .then((res) async {
        if (!res.success) {
          toast(res.msg);
          return;
        }

        toast(res.msg);
        Navigator.of(context).pop();
        Navigator.of(context).pop();
        eventBus.fire(EventRefreshPurshase());
      });
    });
  }
}
